package tests;

import common.Utils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class LovePage extends Utils {
    // 指定页面的 URL
    private static String url = "http://127.0.0.1:8080/loveMusic.html";
    // 设置显式等待
    private WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2));
    public LovePage() {
        super(url);
    }

    // 检查页面是否正确加载
    public void lovePageRight() {
        driver.findElement(By.cssSelector("body > div.container > div:nth-child(3) > a"));
        String title = driver.getTitle();
        assert title.equals("喜欢音乐列表");
    }

    // 检查喜欢音乐查询功能
    public void selLoveMusic() {
        WebElement input = driver.findElement(By.cssSelector("#exampleInputName2"));
        input.sendKeys("李宇春 - 咏春");
        WebElement select = driver.findElement(By.cssSelector("#submit1"));
        select.click();
        List<WebElement> result = driver.findElements(By.cssSelector("#info > tr"));
        assert result.size() == 1;

        input.clear();
        input.sendKeys("无涯");
        select.click();
        result = driver.findElements(By.cssSelector("#info > tr"));
        assert result.size() >= 1;

        input.clear();
        select.click();
        result = driver.findElements(By.cssSelector("#info > tr"));
        assert result.size() >= 1;

        input.clear();
        input.sendKeys("没有这个音乐");
        select.click();
        result = driver.findElements(By.cssSelector("#info > tr"));
        assert result.size() == 0;
        input.clear();
    }

    // 检查取消喜欢音乐功能
    public void delLoveMusic() throws InterruptedException {
        driver.findElement(By.cssSelector("#exampleInputName2")).sendKeys("");
        driver.findElement(By.cssSelector("#submit1")).click();
        int index = driver.findElements(By.cssSelector("#info > tr")).size();
        driver.findElement(By.cssSelector("#del0")).click();
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        assert alert.getText().equals("取消喜欢音乐成功!");
        alert.accept();
    }

    // 检查回到大厅的按钮功能
    public void loveBack() {
        driver.findElement(By.cssSelector("body > div.container > div:nth-child(3) > a")).click();
        String title = driver.getTitle();
        assert title.equals("在线音乐列表");
    }
}
